package com.stylefeng.guns.modular.customer.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.util.Convert;
import com.stylefeng.guns.modular.customer.dao.CustomerRelationDao;
import com.stylefeng.guns.modular.customer.service.ICustomerRelationService;
import com.stylefeng.guns.modular.system.dao.CustomerRelationMapper;
import com.stylefeng.guns.modular.system.model.CustomerRelation;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * <p>
 * 客户关联表 服务实现类
 * </p>
 *
 * @author yinjc123
 * @since 2018-04-14
 */
@Service
public class CustomerRelationServiceImpl extends ServiceImpl<CustomerRelationMapper, CustomerRelation> implements ICustomerRelationService {

    @Autowired
    private CustomerRelationDao customerRelationDao;

    @Override
    public Set<Long> getRelationCustomerIds(Integer customerId) {
        return customerRelationDao.selectRelationCustomerIds(customerId);
    }


    @Override
    @Transactional
    public void setRelation(Integer customerId, String ids) {
        // 删除该角色所有的权限
        this.customerRelationDao.deleteRelations(customerId);

        // 添加新的权限
        Integer[] relationIds = Convert.toIntArray(true, Convert.toStrArray(",", ids));
        Map<Integer, Integer> map = new HashMap<>();

        //判断是否重复添加
        for (Integer relationId : relationIds) {
            //判断是否重复关联
            Integer num = MapUtils.getInteger(map, relationId, 0);
            if (num >= 1) {
                throw new GunsException(HttpStatus.BAD_REQUEST.value(), "不能重复关联");
            }
            map.put(relationId, ++num);

            //判断是否关联自己
            if (relationId.equals(customerId)) {
                throw new GunsException(HttpStatus.BAD_REQUEST.value(), "不能关联自己");
            }

            //写入数据库
            CustomerRelation relation = new CustomerRelation();
            relation.setMainCustomerId(customerId);
            relation.setSubCustomerId(relationId);
            insert(relation);

        }
    }

    @Override
    public void unRelation(Integer customerId, Integer relationId) {
        this.customerRelationDao.unRelation(customerId, relationId);
    }

}
